package com.yuhanginfo.modules.web.web;

import java.util.HashMap;
import java.util.Map;


import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yuhanginfo.common.web.BaseController;
import com.yuhanginfo.modules.web.util.WebUserUtils;
import com.yuhanginfo.modules.web.entity.WebYongUser;
import com.yuhanginfo.modules.web.service.WebClassService;
import com.yuhanginfo.modules.web.service.WebYongUserService;

/**
 * 用户信息管理
 * @author yinhao
 * @version 2017-10-30
 */
@Controller
@RequestMapping(value = "${frontPath}/userInfo")
public class WebUserInfoController extends BaseController {

	@Autowired
	private WebClassService webClassService;
	
	@Autowired
	private WebYongUserService webYongUserService;
	
	@RequiresPermissions("user")
	@RequestMapping(value = "")
	public String index(Model model) {
		model.addAttribute("allClassesList",webClassService.getAllClasses());
		model.addAttribute("actionCenter", "userInfo");
		model.addAttribute("user", WebUserUtils.getNoCacheYong(WebUserUtils.getYongUser().getId()));
		return "modules/web/webUserInfo";
	}
	
	@RequiresPermissions("user")
	@RequestMapping(value = "update" , method = RequestMethod.POST)
	public String update(WebYongUser user , Model model) {
		Map<String,Object> result = new HashMap<String,Object>();
		user.setId(WebUserUtils.getYongUser().getId());
		if(user.getPassword() != null && !"".equals(user.getPassword())){
			user.setPassword(WebYongUserService.entryptPassword(user.getPassword()));
		}
		webYongUserService.save(user);
		user = WebUserUtils.getYong(user.getId());
		WebUserUtils.clearWebCache(user);
		result.put("resultCode", "1");
		result.put("resultMessage", "修改成功,请重新登录");
		model.addAllAttributes(result);
		return this.index(model);
	}
	
	@RequiresPermissions("user")
	@RequestMapping(value = "toPassword")
	public String toPassword(Model model) {
		model.addAttribute("actionCenter", "userInfo");
		return "modules/web/webUserInfoPassword";
	}
	
	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "checkPassword", method = RequestMethod.POST)
	public boolean checkPassword(String checkPassword) {
		return webYongUserService.validatePassword(checkPassword, WebUserUtils.getYongUser().getPassword());
	}
}